import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { getCartListApi } from "@/apis/cart";
import { addCartApi } from "@/apis/cart";
import { deleteCartApi } from "@/apis/cart";
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

export const useCartStore = defineStore('cart', () => {

    const cartList = ref([]);
    const cartNum = ref(0);
    const cartTotalPrice = ref(0);

    const addCart = async (skuId, count) => {
        const res = await addCartApi(skuId, count);
        if (res.code == 1) {
            ElMessage({
                message: '加入购物车成功',
                type: 'success',
            });
        }
    }

    const getCartList = async () => {
        const res = await getCartListApi();
        //获取购物车列表
        cartList.value = res.result;
        // 计算购物车商品总价格
        console.log("cartlist",cartList.value)

        cartTotalPrice.value = computed(() => {
            return cartList.value.reduce((total, item) => {
                return total + item.count * item.nowPrice;
            }, 0);
        });

        // 计算购物车商品总数量
        cartNum.value = computed(() => {
            return cartList.value.reduce((total, item) => {
                return total + item.count;
            }, 0);
        });
        console.log(1634698749787);
    }


    const deleteCart = async (ids) => {
        const res = await deleteCartApi(ids);
        if (res.code == 1) {
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
        }
    }

    return {
        cartList,
        cartNum,
        cartTotalPrice,
        addCart,
        getCartList,
        deleteCart
    }
},
{
    persist: true,
})